package com.lagou.listener;

import com.lagou.entity.Order;
import com.lagou.repository.OrderRepository;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
@RocketMQMessageListener(topic = "tp_order", consumerGroup = "order_consumer")
public class OrderListener implements RocketMQListener<Order> {

    @Autowired
    private OrderRepository orderRepository;
    @Resource
    private RedisTemplate<String, Integer> redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(Order order) {

        System.out.println("创建订单");
        orderRepository.save(order);

        //库存减1
        redisTemplate.opsForValue().increment("goods_count", -1);

        Message message = new Message("tp_delay_pay", order.getOrderId().getBytes());
        org.springframework.messaging.Message springMessage = RocketMQUtil.convertToSpringMessage(message);

        rocketMQTemplate.asyncSend(message.getTopic(), springMessage, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {

            }

            @Override
            public void onException(Throwable e) {

            }
        }, 3000, 4);
    }
}
